<!--
禁止修改!此文件是产品代码的一部分，后续可能变更或者不再开放。
若有问题，请参考前端相关二开文档。
-->
<template>
  <div class="setting">
    <div class="setting-item">
      <ul>
        <li>
          <div>
            <span class="text">{{ $t('languages.common.version') }}</span>
            <span class="text">V{{ version }}</span>
          </div>
          <div class="icon"></div>
        </li>
        <li @click="showToggleLang">
          <div>
            <span class="text">{{
              $t('languages.common.toggleLanguage')
            }}</span>
            <span class="text">{{ curLanguage }}</span>
          </div>
          <div class="icon">
            <i class="icon aufontAll h-icon-all-right-o"></i>
          </div>
        </li>
        <li @click="showChangeCurrentDept">
          <div>
            <span class="text">{{
              $t('languages.common.currentDeptment')
            }}</span>
            <span class="text">{{ currentDeptName }}</span>
          </div>
          <div v-if="userDeptmentList.length > 1" class="icon">
            <i class="icon aufontAll h-icon-all-right-o"></i>
          </div>
        </li>
      </ul>
    </div>
    <H3Actionsheet
      v-model="showActionSheet"
      class="sheet-adjust"
      :menus="actionSheetMenus"
      showCancel
      :cancelText="cancelText"
      @on-click-menu="clickActionSheetMenu"
    />
    <H3Actionsheet
      v-model="showDeptmetActionSheet"
      class="sheet-adjust"
      :menus="currentDeptActionSheetMenus"
      showCancel
      :cancelText="cancelText"
      @on-click-menu="clickCurrentDeptActionSheetMenu"
    />
  </div>
</template>
<script lang="ts">
import { Component, Vue, Watch } from 'vue-property-decorator';

import { H3Actionsheet } from 'h3-mobile-vue';

import { utils } from 'cloudpivot/common';
import { OAuthApi } from 'cloudpivot/api';
import * as platform from 'cloudpivot-platform/platform';
import { namespace } from 'vuex-class';
import { filterUserInfo } from 'cloudpivot/common/src/utils/filter-userInfo';
const UserModule = namespace('System/User');

@Component({
  name: 'Setting',
  components: {
    H3Actionsheet,
  },
})
export default class Setting extends Vue {
  @UserModule.State('loginedUserInfo') userInfo!: any;

  @UserModule.Mutation('setUserInfo') setUserInfo: any;

  showActionSheet: boolean = false;

  showDeptmetActionSheet: boolean = false;

  actionSheetMenus: Array<any> = [];

  currentDeptActionSheetMenus: Array<any> = [];

  cancelText: string = '取消';

  currentDept: any = {};

  userDeptmentList: any[] = [];

  get curLanguage() {
    (window as any).pageTitle = `${this.$t('languages.common.settings')}`;
    platform.service.setTitle(`${this.$t('languages.common.settings')}`);
    switch (this.$i18n.locale) {
      case 'zh':
        return '中文';
      case 'en':
        return 'English';
      default:
        return '';
    }
  }

  get currentDeptName() {
    return this.currentDept.fullname || this.currentDept.name;
  }

  get version() {
    return this.$store.state.config.systemVersion;
  }

  mounted() {
    this.setSheetMenus();

    this.initUserCurrentDeptInfo();
  }

  /*
   * 设置语言菜单国际化
   */
  setSheetMenus() {
    if (this.$i18n.locale === 'en') {
      this.cancelText = 'Cancel';
      this.actionSheetMenus = [
        {
          label: '中文',
          type: 'Default',
          value: 'zh',
        },
        {
          label: 'English',
          type: 'Default',
          value: 'en',
        },
      ];
    } else {
      this.cancelText = '取消';
      this.actionSheetMenus = [
        {
          label: '中文',
          type: 'Default',
          value: 'zh',
        },
        {
          label: 'English',
          type: 'Default',
          value: 'en',
        },
      ];
    }
  }

  /**
   * 切换语言
   */
  toggleLanguage(lang: string) {
    this.$i18n.locale = lang;
    localStorage.setItem('locale', this.$i18n.locale);
    this.setSheetMenus();
    this.$forceUpdate();
  }

  showToggleLang() {
    this.showActionSheet = true;
  }

  clickActionSheetMenu(value: any) {
    if (value === 'cancel') {
      return;
    }
    this.toggleLanguage(value);
  }

  @Watch('showActionSheet')
  onShowActionSheetChange(v: boolean) {
    if (!v) {
      setTimeout(() => {
        utils.Bus.$emit('toggleNavbar', !v);
      }, 100);
    } else {
      utils.Bus.$emit('toggleNavbar', !v);
    }
  }

  initUserCurrentDeptInfoTimeout: any = null;

  /**
   * 初始化用户当前部门信息
   */
  initUserCurrentDeptInfo() {
    if (this.userInfo) {
      if (this.initUserCurrentDeptInfoTimeout) {
        clearTimeout(this.initUserCurrentDeptInfoTimeout);
      }
      this.getUserDeptmentList(this.userInfo.id);
      this.currentDept = {
        id: this.userInfo.currentDeptId || this.userInfo.departmentId,
        name: this.userInfo.currentDeptName || this.userInfo.departmentName,
        fullName: this.userInfo.currentDeptId
          ? ''
          : this.userInfo.parentDepartmentName,
      };
    } else {
      this.initUserCurrentDeptInfoTimeout = setTimeout(() => {
        this.initUserCurrentDeptInfo();
      }, 100);
    }
  }

  // 获取用户部门列表
  getUserDeptmentList(id: string) {
    OAuthApi.getUserDeptmentList(id).then((res: any) => {
      if (res.errcode === 0) {
        const deptList: any = res.data;
        this.userDeptmentList = deptList.map((dept) => {
          return {
            id: dept.deptId,
            name: dept.deptName.split('/').pop(),
            fullName: dept.deptName,
          };
        });
        this.currentDeptActionSheetMenus = this.userDeptmentList.map((dept) => {
          return {
            label: dept.fullname || dept.name,
            type: 'Default',
            value: dept.id,
          };
        });
        let deptment = this.userDeptmentList.find(
          (dept) => dept.id === this.currentDept.id,
        );
        if (!deptment) {
          deptment = deptList.find((dept) => dept.isMain);
          this.onUserCurrrentDeptChange(deptment.deptId);
        }
        this.currentDept = {
          id: deptment.id || deptment.deptId,
          name: deptment.name || deptment.deptName.split('/').pop(),
          fullName: deptment.fullName || deptment.deptName,
        };
      }
    });
  }

  onUserCurrrentDeptChange(value: any) {
    const deptment = this.userDeptmentList.find((dept) => dept.id === value);
    this.currentDept = deptment;
    OAuthApi.updateUserCurrentDept({
      currentDeptId: deptment.id,
      currentDeptName: deptment.name,
    }).then((res: any) => {
      if (res.errcode === 0) {
        this.$message.success(res.errmsg);
        this.userInfo.currentDeptId = this.currentDept.id;
        this.userInfo.currentDeptName = this.currentDept.name;
        this.setUserInfo(this.userInfo);
        window.sessionStorage.setItem(
          'user',
          JSON.stringify(filterUserInfo(this.userInfo)),
        );
      }
    });
  }

  clickCurrentDeptActionSheetMenu(value: any) {
    console.log(value);
    if (value === 'cancel') {
      return;
    }
    this.onUserCurrrentDeptChange(value);
  }

  showChangeCurrentDept() {
    if (this.userDeptmentList.length > 1) {
      this.showDeptmetActionSheet = true;
    }
  }
}
</script>
<style lang="less">
@import '~cloudpivot/common/styles/mixins.less';
.setting {
  .setting-item {
    .px2rem(margin-top, 16px);
    ul {
      li {
        background: white;
        display: flex;
        justify-content: space-between;
        align-items: center;
        .px2rem(padding, 32px);
        div {
          span {
            .px2rem(font-size, 30px);
            display: inline-block;
            line-height: 1;
            &:first-of-type {
              .px2rem(width, 168px);
              text-align: left;
              .px2rem(font-size, 26px);
              .px2rem(line-height, 40px);
              font-weight: 400;
              color: rgba(17, 18, 24, 0.5);
            }
            &:last-of-type {
              .px2rem(margin-left, 24px);
              .px2rem(font-size, 30px);
              .px2rem(height, 44px);
              .px2rem(line-height, 44px);
              color: #111218;
            }
          }
        }
        .icon {
          color: #707481;
          .px2rem(font-size, 26px);
        }
      }
      li {
        border-bottom: 1px solid #f1f2f3;
      }
      li:lase-of-type {
        border-bottom: none;
      }
    }
  }
  .sheet-adjust {
    .h3ui-actionsheet__menu,
    .h3ui-actionsheet__action,
    .h3ui-actionsheet__cell {
      color: #111218;
      .px2rem(font-size, 32px);
      border-radius: 0;
    }
    .h3ui-actionsheet,
    .h3ui-actionsheet__menu {
      border-radius: 12px 12px 0px 0px;
    }
    .h3ui-actionsheet__cell {
      .px2rem(height, 112px);
      .px2rem(line-height, 112px);
    }
    .h3ui-actionsheet__cell:before {
      border-top: 1px solid rgba(209, 211, 228, 0.65);
    }
    .h3ui-actionsheet__cell:first-child {
      border-top: unset;
    }
    .h3ui-actionsheet__cell:before {
      height: 0 !important;
    }
    .h3ui-actionsheet__action {
      .px2rem(margin-top, 16px);
    }
    .h3ui-actionsheet-cancel-button-mask {
      background: #f1f2f3;
      border-top: none;
      top: -8px;
      .px2rem(height, 16px);
    }
  }
}
</style>
